const util = require('../../utils/util.js');
const trackdata = require('data/trackdata.js');

const setting = {
    scale: 18, //缩放
    rotate: 0,
    skew: 50,
    isOverlooking: true,
    isShowPoi: true,
    isenableBuilding: true,
    is3D:false
};

const opIconSources=[
    {id:'settings',classname:'icon-settings'},
    {id:'pitch',classname:'icon-map_pitch'}
]

const testIconSources=[
    {id:'sign',classname:'icon-sign'},
    {id:'playcircle',classname:'icon-play_circle'},
    {id:'luggage',classname:' icon-luggage'}
]
Page({
    data: {
        location: '',
        markers: '', //地图markers
        setting: setting,
        includePoints: '',
        // polygons:[
        //   {...polygon1},
        //   {...polygon2}
        // ], //多边形
        polygons: '',
        floorname: '', //楼层名
        floornum: '', //楼层号
        floor: trackdata.floor,
        ifcontent: false, //是否显示
        activeItem: 1,
        nowfloornum: '', //当前楼层
        movepoints: [], //marker移动坐标点合集
        mapCtx: '',
        polyline: [{ ...trackdata.polyline }],
        resdata: [], //存储服务器响应数据
        opIconSources:opIconSources,
        testIconSources:testIconSources
    },
    onLoad: function (options) {
        this.defaultFloor();

        // 获取当前的地理位置、速度
        // wx.getLocation({
        //   type: 'wgs84',
        //   success (res) {
        //     console.log('latitude: '+res.latitude+';longitude: '+res.longitude+';accuracy: '+res.accuracy);
        //   }
        // });
    },
/**
 * @param {} e 
 */
onItemClick:function(e){

},
    // 弹出/关闭切换楼层
    popCheckFloor: function (e) {
        var ifcontent = this.data.ifcontent;
        this.setData({
            ifcontent: !ifcontent,
        });
    },
    // 点击页面其他地方关闭弹窗
    close: function(e){
        this.setData({
			ifcontent:false
		});
    },
    /**
     * @function 初次进入页面设置默认楼层,渲染地图
     */
    defaultFloor: function () {
        console.log('defaultFloor');
        const floordata = trackdata.floor;
        let number = trackdata.floor[0]['number'];
        let url = trackdata.floor[0]['url'];
        var requestData = util.joinUrl(url);
        util.wxRequest(requestData).then(res => this.processPolygonData(res));
        this.setData({
            nowfloornum: number,
        });
    },
    /**
     * @function 切换楼层
     * @param {*} e 当前点击元素
     */
    selectFloor: function (e) {
        var that = this;
        const id = e.currentTarget.dataset['id'];
        const floordata = trackdata.floor;
        console.log(floordata);
        var url, number;
        var requestData;
        floordata.map((item, index) => {
            if (item.id == id) {
                url = item.url;
                number = item.number;
            }
        });
        requestData = util.joinUrl(url);
        console.log(requestData);
        util.wxRequest(requestData).then(function (res) {
            that.processPolygonData(res);
        });
        that.setData({
            activeItem: id,
            nowfloornum: number,
        });
    },
    // 确认
    affirm: function () {
        this.setData({
            ifcontent: false,
        });
    },
    /**
     * @function 处理服务端geojson数据，获取coordinates
     * @param {array} res geojson数据
     * @function {function} callback 回调函数
     */
    processPolygonData: function (res) {
        var that = this;
        let resa = util.deepClone(res.data.features);
        // console.log(resa);
        // var points;
        var polygons = []; //存储所有多边形所有属性，包括	strokeColor/fillColor/strokeWidth:10/zIndex
        var points = []; //	points: [	{latitude: ,longitude: }]
        resa.map(item1 => {
            var coordinates = item1.geometry.coordinates;
            coordinates.map(item2 => {
                item2.map(item3 => {
                    var coorarr = item3.map(item4 => {
                        return { latitude: item4[1], longitude: item4[0] };
                    });
                    points.push(coorarr);
                    // console.log(points)
                });
            });
        });

        polygons = that.setobj(points, that.setstyle);
        // console.log(polygons)
        // console.log(points[0]);
        var centerpoint = that.getCenter(points);
        that.setData({
            location: {
                latitude: centerpoint[0],
                longitude: centerpoint[1],
            },
            includepoints: points,
            polygons: polygons,
        });
    },
    /**
     * @function 处理points数组为小程序polygons格式
     * @param {array} points 多边形经纬度数组
     * @param {function} callback
     * @returns
     */
    setobj: function (points, callback) {
        var polygons = [];
        for (let i = 0; i < points.length; i++) {
            var robj = {};
            robj.points = points[i];
            callback(robj, '#2291FFAA', '#8DC5FCAA', 2);
            polygons.push(robj);
        }
        return polygons;
    },
    /**
     * @function设置多边形属性
     * @param {obj} robj:{points: [{latitude: , longitude: }]}
     * @param {string} strokeColor 描边的颜色
     * @param {string} fillColor
     * @param {number} strokeWidth
     */
    setstyle: function (robj, strokeColor, fillColor, strokeWidth) {
        robj.strokeColor = strokeColor;
        robj.fillColor = fillColor;
        robj.strokeWidth = strokeWidth;
        // console.log(robj)
    },
    /**
     * @function 取一组经纬度中心点
     * @param {array} pointArray
     * @returns  返回中心点 经纬度数组 [centerLatitude, centerLongitude]
     */
    getCenter: function (pointArray) {
        var sortedLongitudeArray;
        var sortedLatitudeArray;
        var centerLongitude;
        var centerLatitude;
        // console.log('------------------------------------------------');
        // console.log(pointArray);
        pointArray.map(item => {
            if (Array.isArray(item)) {
                sortedLongitudeArray = item.map(citem => citem.longitude).sort(); //首先对经度进行排序，红色部分是array中经度的名称
                sortedLatitudeArray = item.map(citem => citem.latitude).sort(); //对纬度进行排序，红色部分是array中纬度的名称
                centerLongitude = (
                    (parseFloat(sortedLongitudeArray[0]) +
                        parseFloat(sortedLongitudeArray[sortedLongitudeArray.length - 1])) /
                    2
                ).toFixed(4);
                centerLatitude = (
                    (parseFloat(sortedLatitudeArray[0]) +
                        parseFloat(sortedLatitudeArray[sortedLatitudeArray.length - 1])) /
                    2
                ).toFixed(4);
            }
        });
        console.log(centerLongitude + 'kkk' + centerLatitude);
        console.log(sortedLongitudeArray);
        return [centerLatitude, centerLongitude];
    },
    /**
     * @function 地图添加标记(未调用)
     * @param {array} marker 地图标记数组  trackdata.markers
     */
    setmarkers: markers => {
        this.setData({
            markers: markers,
        });
    },
    /**
     * @function 递归方式降维多维数组(未调用)
     * @param {array} arr  需要降维的数组
     */
    reduceDimension: function (arr) {
        let ret = [];
        let toArr = function (arr) {
            arr.forEach(function (item) {
                item instanceof Array ? toArr(item) : ret.push(item);
            });
        };
        toArr(arr);
        return ret;
    },
    /**
     *
     * @param {*} arr (未调用)
     */
    flattenDeep: function (arr) {
        return arr.reduce(function (acc, val) {
            return Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val);
        }, []);
    },
    /**
     * @function 字符串按规定字符分隔返回新数组 (未调用)
     * @param {string} stringToSplit  需拆分为数组的字符串
     * @param {string} separator  每个拆分应发生的点的字符串
     */
    splitString: function (stringToSplit, separator) {
        var arrayOfStrings = stringToSplit.split(separator);
        return arrayOfStrings;
    },
    // movepoints：经纬数组 (未调用)
    confirmFloor: function (e) {
        const mapCtx = wx.createMapContext('trackMap');
        const points = this.data.polygons[0].points;
        var movepoints = this.data.movepoints;
        console.log(movepoints);
        mapCtx.includePoints({
            points,
        });
        mapCtx.moveAlong({
            markerId: 1,
            autoRotate: true,
            path: movepoints,
            duration: 5000,
        });
        this.setData({
            ifcontent: false,
        });
    },
    // 计算scrollTop(未调用)
    getscrollTop: function () {
        var that = this;
        const query = wx.createSelectorQuery();
        console.log(query.select('#selectBox'));
        query
            .select('#selectBox')
            .boundingClientRect(function (rect) {
                var hh = 0;
                hh += rect.height;
                hh = hh - 280;
                that.setData({
                    scrollTop: hh,
                });
                console.log('scroll' + hh);
            })
            .exec();
    },
    // // 切换楼层（old abandon）
    // chooseFloor: function (e) {
    //     const id = e.currentTarget.dataset['id'];
    //     var points = [];
    //     var number;
    //     const floor = JSON.parse(JSON.stringify(this.data.floor));
    //     floor.forEach(function (item, i) {
    //         if (item.id == id) {
    //             points = [...item.points];
    //             number = item.number;
    //         }
    //     });
    //     console.log(points);
    //     this.setData({
    //         activeItem: id,
    //         nowfloornum: number,
    //         movepoints: points,
    //     });
    // }
});
